package start.spring.basic.util.common;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * ****************************************************************************
 * 兼容前端JSEncrypt库的rsa加解密工具类
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2020年5月11日
 * 
 * @from: https://www.jianshu.com/p/ff8281f034f4
 ******************************************************************************
 */
public class RSACoder {
	
    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    public static byte[] decryptBASE64(String key) {
        return Base64.decodeBase64(key);
    }

    public static String encryptBASE64(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       加密数据
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        // 解密由base64编码的私钥
        byte[] keyBytes = decryptBASE64(privateKey);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取私钥匙对象
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data);
        return encryptBASE64(signature.sign());
    }

    /**
     * 校验数字签名
     *
     * @param data      加密数据
     * @param publicKey 公钥
     * @param sign      数字签名
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign)
            throws Exception {
        // 解密由base64编码的公钥
        byte[] keyBytes = decryptBASE64(publicKey);
        // 构造X509EncodedKeySpec对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取公钥匙对象
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(data);
        // 验证签名是否正常
        return signature.verify(decryptBASE64(sign));
    }

    /**
     * 私钥解密
     *	
     * @param data
     * @param key
     * @return
     * @throws Exception
     * @since           1.0
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String key) throws Exception{
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        
        return decryptedData;
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String data, String key)
            throws Exception {
        return new String(decryptByPrivateKey(decryptBASE64(data),key));
    }

    /**
     * 公钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        
        return decryptedData;
    }
    
    /**
     * 公钥解密
     *	
     * @param data
     * @param key
     * @return
     * @throws Exception
     * @since           1.0
     */
    public static String decryptByPublicKey(String data, String key)
            throws Exception {
    	return new String(decryptByPublicKey(decryptBASE64(data),key));
    }

    /**
     * 公钥加密
     *
     * @param sourcedata
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String sourcedata, String key)
            throws Exception {
        // 对公钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        
        byte[] data = sourcedata.getBytes();
        		
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        
        return encryptBASE64(encryptedData);
    }

    /**
     * 私钥加密
     *
     * @param sourcedata
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptByPrivateKey(String sourcedata, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        
        byte[] data = sourcedata.getBytes();
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        
        return encryptBASE64(encryptedData);
    }
    

    /**
     * 取得私钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Key> keyMap){
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 取得公钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Key> keyMap) {
        Key key = keyMap.get(PUBLIC_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 初始化密钥
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Key> initKey() {
    	Map<String, Key> keyMap = new HashMap<>(4);
		try {
			KeyPairGenerator keyPairGen = KeyPairGenerator
			        .getInstance(KEY_ALGORITHM);
			keyPairGen.initialize(1024);
	        KeyPair keyPair = keyPairGen.generateKeyPair();
	        
	        // 公钥
	        keyMap.put(PUBLIC_KEY, keyPair.getPublic());
	        // 私钥
	        keyMap.put(PRIVATE_KEY, keyPair.getPrivate());
	        
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
        return keyMap;
    }
    
//   public static void main(String[] args) {
//		try {
//
//			Map<String, Key> keyMap = RSACoder.initKey();
//			String publicKey = RSACoder.getPublicKey(keyMap);
//	    	String privateKey = RSACoder.getPrivateKey(keyMap);
//	        System.err.println("公钥: \n\r" + publicKey);
//	        System.err.println("私钥： \n\r" + privateKey);
//
//	        System.err.println("公钥加密——私钥解密");
//	        String inputStr = "{\"total\":23,\"createUserName\":\"哇塞成功了\",\"bxdList\":[{\"bxdCode\":\"12345678\",\"bxrName\":\"报销人\",\"projectCode\":\"3101\",\"categoryList\":[{\"money\":\"100.23\",\"dsc\":\"餐费\",\"categoryCode\":\"66051501\"},{\"money\":\"2.77\",\"dsc\":\"手机费\",\"categoryCode\":\"66051402\"}],\"deptCode\":\"6666\",\"userCode\":\"111\"},{\"bxdCode\":\"4567123\",\"bxrName\":\"报销人\",\"projectCode\":\"3101\",\"categoryList\":[{\"money\":\"100.23\",\"dsc\":\"餐费\",\"categoryCode\":\"66051501\"},{\"money\":\"2.77\",\"dsc\":\"手机费\",\"categoryCode\":\"66051402\"}],\"deptCode\":\"6666\",\"userCode\":\"111\"}]}";
//	        //公钥加密
//	        String encodedData = RSACoder.encryptByPublicKey(inputStr, publicKey);
//	        //私钥解密
////            encodedData = "muAGO6xWA8aHvJ2/svVPpG2LvAxNMjUX21TrmBotlWHW4y7G4kz2iEd1KN79INlfYsTYfusckq9TPoPI31tyriEWHKjYJWC7rjGKt0JxY0NNbCJCAPYpelwBoADhkSSkuJByvZKpNvw0rrmenL7IWnmZhXRdEb+Os5lifOJZowe0MyZ5QsdL+pGoXJT4s3RxJDGz91MzR/wJFffh86zMGZHEAWC6306FnApucRqBYnpLnPArwTGyUEDx40F08VwAI4mFl9ustfjFZoqhmSCVFTfcSZLnIhxU4i2GoRmquJGgA47cNPrO+RKhxwxgBnQGbxKWg10L6gu+6QmJaQdWdg==";
////            privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL6bXH6ToRlWeXg6O52i0DEnwycy1VAMEJSiKx9XvpRwKoteO3n6Y6Hbha2XuxWvGsNlHrCa99Iw8x/5NnJR8AZHX4Jp+CRKdLZsem8ayOnAWvAL1YaEVUxlldgEqhcEV0LiUXEsdYyUlqwsGlMps+QlPiMpY3JXAdiDQMN7fdebAgMBAAECgYALq929DnMl5wqnFwHBhE+1QtcLVmyDa0m0oD19vNS5qCiiwhFoRbHGHngQCiN1j3RXFKENdV/Jah/pDEyOMYA99uaqApRN7M6jrQtyLzMg4CQi2KfnpwMHf2m4RdvqRWnJ9jnt981cevPA6uRfWop9kS7qA34bBf08aRIYJKjiQQJBAPuaQFQOy6RhvULeCHLVuawT+VZBH/tkwDh6GkuSe7G9NgW/NbNEq8KuclSSBo6bUx3kY02HOyXIWjgCB/NsNjsCQQDB8DI/3fWB/sizRIs7WtiaLWI2lZfJxfcg2Ka4gY7ctYVdcHk96BKfPacT3J4TGZSO4RrdcorBMCdz2UneYO4hAkEAk5MeOC+Vco2BnT7uZazGgxAUJ2t7ftDRjk7QLZN1ygLZNPW6YbPdqwr3NHOSNQMV9WqIdGjlYHvrrv5B+511EQJAaX1917+kC1HLWbevBFol97c39Pjp15cXFYbDKRlP3D3gjTLgwAu8FWIzv1oBoeIILK/FLS9gyjSnQRywUYXoAQJAW+SluSfnS/MIuoHVZkRvx4gDVVdzh7eGIZfyceGM1QTGcjhtss/DFXwKQe1LG6Xwqst6sQm+jvMGp8Vhmcq16Q==";
//	        String decodedData = RSACoder.decryptByPrivateKey(encodedData,privateKey);
//	        System.err.println("公钥加密前: " + inputStr + "\n\r" + "私钥解密后: " + decodedData);
//
//	        inputStr = "{\"total\":2223,\"createUserName\":\"哇塞aaa了\",\"bxdList\":[{\"bxdCode\":\"12345678\",\"bxrName\":\"报销人\",\"projectCode\":\"3101\",\"categoryList\":[{\"money\":\"100.23\",\"dsc\":\"餐费\",\"categoryCode\":\"66051501\"},{\"money\":\"2.77\",\"dsc\":\"手机费\",\"categoryCode\":\"66051402\"}],\"deptCode\":\"6666\",\"userCode\":\"111\"},{\"bxdCode\":\"4567123\",\"bxrName\":\"报销人\",\"projectCode\":\"3101\",\"categoryList\":[{\"money\":\"100.23\",\"dsc\":\"餐费\",\"categoryCode\":\"66051501\"},{\"money\":\"2.77\",\"dsc\":\"手机费\",\"categoryCode\":\"66051402\"}],\"deptCode\":\"6666\",\"userCode\":\"111\"}]}";
//
//	        //私钥加密
//	        encodedData = RSACoder.encryptByPrivateKey(inputStr, privateKey);
//	        //公钥解密
//	        decodedData = RSACoder.decryptByPublicKey(encodedData, publicKey);
//	        System.err.println("私钥加密前: " + inputStr + "\n\r" + "公钥解密后: " + decodedData);
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
}

